package cn.edu.xust.util;

import cn.edu.xust.configuration.exception.Default200Exception;
import cn.edu.xust.configuration.exception.ErrorConstant;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.*;


@Slf4j
public class WebSend {
    public static final Logger logger= LoggerFactory.getLogger(WebSend.class);
    private static final int TIME_OUT = 2;



    /**
     * 发送Get请求
     * @param url
     * @param param
     * @return
     */
    public static String sendGet(String url, String param,String token) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString=url;
            if(!StringUtil.isNullOrEmpty(param)) {
                urlNameString = url + "?" + param;
            }
//            logger.info("此处有个请求url:"+urlNameString);

            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //添加token头
            if(token!=null) {
                connection.setRequestProperty("authorization",token);
            }
            // 建立实际的连接
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.warn(e.getMessage());
            throw new RuntimeException(e.getMessage());
//            return "发送出错";
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }



    public static String sendGet(String url, Map<String,Object> param,String token) {
        String result = "";
        BufferedReader in = null;
        try {
//            String urlNameString = url + "?" + param;
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            param.forEach((k,v)->{
                connection.setRequestProperty(k, (String) v);
            });
            //添加token头
            if(token!=null) {
                connection.setRequestProperty("authorization",token);
            }
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.warn(e.getMessage());
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;

    }

    /**
     * 发送Post请求
     * @param url
     * @param param
     * @return
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Transfer-Encoding", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            out = new PrintWriter(outWriter);
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.info("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String sendPost(String url, Map<String,Object> map,String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn= (HttpURLConnection) realUrl.openConnection();

            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Transfer-Encoding", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if(map!=null && map.get("sign")!=null) {
                conn.setRequestProperty("sign", map.get("sign").toString());
                conn.setRequestProperty("appKey", map.get("appKey").toString());
                conn.setRequestProperty("timestamp", map.get("timestamp").toString());
            }

            //LOCK V3用
            if(map!=null && map.get("Sign")!=null) {
                conn.setRequestProperty("Sign", map.get("Sign").toString());
                conn.setRequestProperty("AppId", map.get("AppId").toString());
                conn.setRequestProperty("Timestamp", map.get("Timestamp").toString());
                conn.setRequestProperty("NonceStr", map.get("NonceStr").toString());
                conn.setRequestProperty("Mode", map.get("Mode").toString());
                conn.setRequestProperty("BodySign", map.get("BodySign").toString());
            }
            logger.info("==============header====================");
            logger.info(conn.getRequestProperties().toString());
            logger.info("==============header====================");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            out = new PrintWriter(outWriter);
            // 发送请求参数
            logger.info("参数=>"+param);
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            int code = conn.getResponseCode();
            if(code>=400){
                InputStream errorStream = conn.getErrorStream();
                in = new BufferedReader(
                        new InputStreamReader(errorStream));
                log.info("错误提示");
                log.info(String.valueOf(in));
                log.info(errorStream.toString());
            }
            else {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
            }
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            log.info(result);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("发送 POST 请求出现异常！"+e.getMessage());
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    public static String sendPostForfrgLockv3(String url, Map<String, Object> params) {

        return "";


    }
    public static String sendPostControl(String url, Map<String,Object> map,String token) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn= (HttpURLConnection) realUrl.openConnection();

            conn.setRequestMethod("POST");
            conn.setConnectTimeout(1500);
            conn.setReadTimeout(1500);
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type","application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Transfer-Encoding", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("authorization",token);
//            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

//            conn.setRequestProperty("sign",map.get("sign").toString());
//            conn.setRequestProperty("appKey",map.get("appKey").toString());
//            conn.setRequestProperty("timestamp",map.get("timestamp").toString());

            logger.info("==============header====================");
            logger.info(conn.getRequestProperties().toString());
            logger.info("==============header====================");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            out = new PrintWriter(outWriter);
            // 发送请求参数
            String obj2string = JsonUtils.obj2string(map);
            logger.info("params=>"+obj2string);
            out.print(obj2string);

            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            int code = conn.getResponseCode();
            if(code>=400){
                InputStream errorStream = conn.getErrorStream();
                in = new BufferedReader(
                        new InputStreamReader(errorStream));
                log.info("错误提示");
                log.info(String.valueOf(in));
                log.info(errorStream.toString());
            }
            else {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
            }
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            log.info(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("发送 POST 请求出现异常！"+e.getMessage());
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    /**
     * post请求
     * @param url
     * @param headerMap  header 参数
     * @param contentMap body 参数
     * @return
     */
    public static String sendPostMap(String url, Map<String, Object> headerMap, Map<String, Object> contentMap) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> content = new ArrayList<NameValuePair>();
        Iterator iterator = contentMap.entrySet().iterator();           //将content生成entity
        while (iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
            content.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
        }
        CloseableHttpResponse response = null;
        try {
            post.addHeader("Content-Type","application/json");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader("Pragma", "no-cache");
            post.addHeader("Accept","*/*");
            post.addHeader("Connection","keep-alive");
            Iterator headerIterator = headerMap.entrySet().iterator();          //循环增加header
            while (headerIterator.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) headerIterator.next();
                post.addHeader(elem.getKey(), elem.getValue());
            }


            logger.info("====================header====================");
            log.info(Arrays.toString(post.getAllHeaders()));
            logger.info("====================header====================");

            if (content.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content, "UTF-8");
                post.setEntity(entity);
            }

            response = httpClient.execute(post);            //发送请求并接收返回数据
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();       //获取response的body部分
                result = EntityUtils.toString(entity);          //读取reponse的body部分并转化成字符串
            }
            if(response!=null){
                log.info(response.getEntity().toString());
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }



    public static String doPost(String url, String json,Map<String, String> headerMap){
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            headerMap.forEach(post::addHeader);
            HttpResponse res = client.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(response==null){
            return null;
        }
        if(!response.get("code").equals(0)){
            log.info("获取失败");
        }
        JSONObject data = (JSONObject) response.get("data");
        return data.get("token").toString();
    }

    /**
     * 发送post请求
     * @param url  路径
     * @param jsonObject  参数(json类型)
     * @param encoding 编码格式
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String sendPostJson(String url, JSONObject jsonObject,String encoding) throws ParseException, IOException{
        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(s);
        log.info("请求地址:"+url);
//        log.info("请求参数:"+nvps.toString());

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
//        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

    public static String sendPostControlForTv(String url, Map<String,Object> map,String token) throws Default200Exception {

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn= (HttpURLConnection) realUrl.openConnection();

            conn.setRequestMethod("POST");
            conn.setConnectTimeout(1500);
            conn.setReadTimeout(1500);
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type","application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Transfer-Encoding", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("authorization",token);
//            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

//            conn.setRequestProperty("sign",map.get("sign").toString());
//            conn.setRequestProperty("appKey",map.get("appKey").toString());
//            conn.setRequestProperty("timestamp",map.get("timestamp").toString());

            logger.info("==============header====================");
            logger.info(conn.getRequestProperties().toString());
            logger.info("==============header====================");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            out = new PrintWriter(outWriter);
            // 发送请求参数
            String obj2string = JsonUtils.obj2string(map);
            logger.info("params=>"+obj2string);
            out.print(obj2string);

            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            int code = conn.getResponseCode();
            if(code>=400){
                InputStream errorStream = conn.getErrorStream();
                in = new BufferedReader(
                        new InputStreamReader(errorStream));
               logger.info("错误提示");
                logger.info(String.valueOf(in));
                logger.info(errorStream.toString());
            }
            else {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
            }
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            log.info(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("发送 POST 请求出现异常！"+e.getMessage());
            throw new Default200Exception(ErrorConstant.tcl_badterminal);
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;






    }
}



